<?php

namespace App\Api\Repositories;

use App\Models\Option as Model;
use Illuminate\Support\Facades\Cache;


class OptionRepositories
{
    protected $eloquentClass = Model::class;

    /**
     * 获取所有的类型
     *
     * @return void
     */
    public function get_types()
    {
        return $this->eloquentClass::$type_text;
    }

    /**
     * 获取全部类型的选项值
     *
     * @return void
     */
    public function get_all_data()
    {
        $data = [];
        foreach ($this->eloquentClass::$type_text as $key => $value) {
            $data[$key] = $this->get_data($key);
        }
        $data['birthday'] = $this->get_data('birthday');
        return $data;
    }

    /**
     * 获取某类型的选项值并加入缓存
     *
     * @param string $type 类型
     * @return void
     */
    public function get_data($type)
    {
        if ($type == 'birthday') {
            $data = [];
            foreach (range(1900, date("Y", time())) as $year) {
                $y = [];
                foreach (range(1, 12) as $month) {
                    $y[] = $month;
                }
                $data[$year] = $y;
            }
            return $data;
        }
        return Cache::remember($type, 86400, function () use ($type) {
            if (in_array($type, ['city', 'college'])) {
                $eloquentClass_data = $this->eloquentClass::where('type', $type)->orderBy('sort', 'asc')->select('option', 'remark')->get();
                $province = $this->get_data('province');
                $data = [];
                foreach ($province as $value) {
                    $data[$value] = [];
                }
                foreach ($eloquentClass_data as $v) {
                    $data[$v->remark][] = $v->option;
                }
                return $data;
            }
            return $this->eloquentClass::where('type', $type)->pluck('option')->toArray();
        });
    }

    /**
     * 根据城市获取省
     *
     * @param string $option
     * @return void
     */
    public function use_city_get_province($option)
    {
        return $this->eloquentClass::where('type', 'city')->where('option', $option)->value('remark') ?? '';
    }

    /**
     * 清除缓存
     *
     * @param string $key 缓存键值，也是option表的type字段
     * @return void
     */
    public function delete_cache($key = '')
    {
        if ($key != '') {
            Cache::pull($key);
        } else {
            foreach ($this->eloquentClass::$type_text as $key => $value) {
                Cache::pull($key);
            }
        }
    }
}
